<!-- 颜色深浅 -->
<template>
  <PageTabelLayout>
    <template #pageHeader>
      <div>
        <div class="search-form divClass" v-if="headerShow">
          <a-form size="small" :model="formQuery" layout="inline">
            <a-form-item label="颜色深浅">
              <a-input
                :style="{ width: '200px' }"
                class="bacClass"
                @press-enter="selectHandler"
                v-model="formQuery.shade"
                allow-clear
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-divisders">
          <a-divider orientation="center">
            <icon-double-up
              v-if="headerShow"
              @click="headerShow = false"
              :strokeWidth="2"
              :size="18"
            />
            <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
          </a-divider>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            :items="['查询', '新增', '删除']"
            @add="addHandler"
            @del="delHandler"
            @select="selectHandler"
          />
        </div>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        class="ag-theme-alpine"
        :defaultColDef="defaultColDef"
        :rowData="table.dataList"
        :columnDefs="cfsValue"
        :localeText="localeTextData"
        :suppressRowClickSelection="true"
      />
    </template>
    <paginationCopys
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="changePage"
      @page-size-change="changeSize"
      style="justify-content: center"
      :page-size="pagination.pageSize"
      :current="pagination.page"
    />
    <a-drawer
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      :ok-loading="saveLoading"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label="颜色深浅"
            :label-col-flex="pageData.labelColFlex"
            field="shade"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '颜色深浅必填' }]"
          >
            <a-input
              v-model="dataForm.shade"
              @blur="dataForm.shade = dataForm.shade?.toUpperCase()"
              class="bacClass"
            />
          </a-form-item>
          <a-form-item
            label="浓度值>="
            :label-col-flex="pageData.labelColFlex"
            field="concentrationGreater"
          >
            <a-input-number
              v-model="dataForm.concentrationGreater"
              class="bacClass"
              :step="0.01"
              :precision="2"
            />
          </a-form-item>
          <a-form-item
            label="浓度值<="
            :label-col-flex="pageData.labelColFlex"
            field="concentrationLess"
          >
            <a-input-number
              v-model="dataForm.concentrationLess"
              class="bacClass"
              :step="0.01"
              :precision="2"
            />
          </a-form-item>
          <a-form-item label="工艺深浅" :label-col-flex="pageData.labelColFlex" field="craftDepth">
            <a-input v-model="dataForm.craftDepth" class="bacClass" />
          </a-form-item>
          <a-form-item label="用坯深浅" :label-col-flex="pageData.labelColFlex" field="greyDepth">
            <a-input v-model="dataForm.greyDepth" class="bacClass" />
          </a-form-item>

          <a-form-item label="用纱深浅" :label-col-flex="pageData.labelColFlex" field="yarnDepth">
            <a-input v-model="dataForm.yarnDepth" class="bacClass" />
          </a-form-item>
          <a-form-item label="备注" :label-col-flex="pageData.labelColFlex">
            <a-textarea
              v-model="dataForm.remark"
              class="bacClass"
              :max-length="{ length: 400 }"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </PageTabelLayout>
</template>

<script lang="ts">
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import { Shade } from '@/interface/basicDataInterface'
  import { ref, reactive, onMounted } from 'vue'
  import { colorDepth } from '@/api/laboratory/index'
  import vaildate from '@/hooks/useValidate'
  import { FormInstance, Message, Modal } from '@arco-design/web-vue'
  import PageTabelLayout from '../pageTabelLayout.vue'
  
  import { localeText } from '@/api/aggridZw'
  import emitter from '@/hooks/useEventBus'
  export default {
    name: 'ColorDepth',
    setup() {
      //隐藏显示头部
      const headerShow = ref<boolean>(true)
      //抽屉保存按钮加载状态
      const saveLoading = ref<boolean>(false)
      const formQuery = reactive<any>({
        shade: '',
      })
      onMounted(() => {
        // 第一个页面需要在刚进入就调用一次  切换tap时也需要调用
        doRefresh()
        emitter.on('refresh-ColorDepth', () => {
          doRefresh()
          gridOption.value.sizeColumnsToFit()
        })
      })
      const colorDepthApi = colorDepth()
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else if (key == 'serial') {
            dataForm[key] = 0
          } else {
            dataForm[key] = ''
          }
        }
        pageData.showAdd = true
        pageData.sideTitle = '新增颜色深浅定义'
      }
      const delHandler = () => {
        let vals = gridOption.value.getSelectedRows().map((v: any) => {
          return v.id
        })
        if (vals.length > 0) {
          Modal.confirm({
            title: '提示',
            content: '确定要批量删除选中数据吗？',
            cancelText: '取消',
            okText: '删除',
            onOk: async () => {
              try {
                const res = await colorDepthApi.delColorDepth([...vals])
                if (res.code === 200) {
                  Message.success('数据删除成功')
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error(res.message)
                }
              } catch (error) {
                console.log(error)
              }
            },
          })
        } else {
          Message.info('请选择需要删除的数据')
        }
      }
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      const editHandler = (record: Shade) => {
        pageData.showAdd = true
        pageData.sideTitle = '编辑颜色深浅定义'
        for (var key in record) {
          dataForm[key] = record[key]
        }
      }
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        saveLoading.value = true
        formRef.value?.validate().then(async (err) => {
          if (!err) {
            if (dataForm.id) {
              try {
                const res = await colorDepthApi.editColorDepth([{ ...dataForm }])
                if (res.code == 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              } catch (error) {
                console.log(error)
              } finally {
                saveLoading.value = false
              }
            } else {
              try {
                const res = await colorDepthApi.addColorDepth([{ ...dataForm }])
                if (res.code == 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              } catch (error) {
                console.log(error)
              } finally {
                saveLoading.value = false
              }
            }
          } else {
            saveLoading.value = false
            console.log(err)
          }
        })
      }
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        theight: number
        tablediv: any
        rHeight: number | undefined
        labelColFlex: string
      }>({
        showAdd: false,
        sideTitle: '新增颜色深浅定义',
        dropDownData: '',
        pageLoading: false,
        theight: 0,
        tablediv: null,
        rHeight: 0,
        labelColFlex: '80px',
      })
      const scrollbar = ref(true)
      const { selectedRowKeys } = useRowSelection()
      async function doRefresh() {
        pageData.pageLoading = true
        try {
          const res = await colorDepthApi.getPageColorDepthList({
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,
            shade: formQuery.shade,
          })
          if (res.code === 200) {
            gridOption.value.sizeColumnsToFit()
            table.handleSuccess(res.data.list)
            gridOption.value.setRowData(res.data.list)
            total.value = res.data.total
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            })
          }
        } catch (error) {
          console.log(error)
        } finally {
          pageData.pageLoading = false
        }
      }
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const dataForm = reactive<Shade>({
        id: null,
        serial: 0,
        createTime: '',
        shade: '',
        concentrationGreater: 0,
        concentrationLess: 0,
        craftDepth: '',
        greyDepth: '',
        yarnDepth: '',
        remark: '',
        createName: '',
      })
      //检验表单是否含有中文的方法
      const hasChiese = vaildate.includeChinese
      const tableColumns = useTableColumn([
        {
          title: '序号',
          key: 'serial',
          dataIndex: 'serial',
          width: 150,
        },
        {
          title: '颜色深浅',
          key: 'shade',
          dataIndex: 'shade',
          width: 150,
        },
        {
          title: '浓度>=',
          key: 'concentrationGreater',
          dataIndex: 'concentrationGreater',
          width: 150,
        },
        {
          title: '浓度<=',
          key: 'concentrationLess',
          dataIndex: 'concentrationLess',
          width: 150,
        },
        {
          title: '工艺深浅',
          key: 'craftDepth',
          dataIndex: 'craftDepth',
          width: 150,
        },
        {
          title: '用坯深浅',
          key: 'greyDepth',
          dataIndex: 'greyDepth',
          width: 150,
        },
        {
          title: '用纱深浅',
          key: 'yarnDepth',
          dataIndex: 'yarnDepth',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 150,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 150,
        },
        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'action',
          width: 150,
          fixed: 'right',
        },
      ])

      //表格方面
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        //调整表格自适应大小
        gridOption.value.sizeColumnsToFit()
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        flex: 1,
      }
      let cfsValue: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
        }
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          // obj["width"] = 100
          obj['cellRenderer'] = {
            template: `<a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                a,
              }
            },
          }
        }

        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      cfsValue = a.concat(cfsValue)
      const total = ref(10)
      const changePage = (val: any) => {
        pagination.page = val
        doRefresh()
      }
      const changeSize = (val: any) => {
        pagination.pageSize = val
        doRefresh()
      }

      const localeTextData: any = ref(localeText)

      return {
        headerShow,
        saveLoading,
        formQuery,
        addHandler,
        delHandler,
        selectHandler,
        editHandler,
        pageData,
        tableColumns,
        scrollbar,
        selectedRowKeys,
        pagination,
        table,
        rowKey,
        dataForm,
        sideOk,
        hasChiese,
        formRef,
        changePage,
        changeSize,
        localeTextData,
        defaultColDef,
        gridReady,
        cfsValue,
        total,
      }
    },
    components: { PageTabelLayout,  },
  }
</script>

<style scoped>
  .main-container {
    height: 100%;
  }
  .aInput {
    width: 270px;
    background: #fff;
    border: 1px solid #c9cdd3;
  }
  :deep(.arco-textarea-wrapper) {
    background: #fff;
    border: 1px solid #c9cdd3;
    width: 270px;
  }
</style>
